import React from 'react'
import logo from '@/assets/images/logo.png'
import wxGong from '@/assets/images/logo.png'
import NewLogo from '@/assets/images/logo.png'

import printJs from 'print-js'
import JsBarcode from 'jsbarcode';


import printStyle from './printStyle'
import { unitConversion } from './unitConversion'
import $ from 'jquery'
function createTable(ths, trs) {
    // 创建数据表格
    const table = $("<table border='0' cellPadding='0' cellSpacing='0' data-pageNo='' style='page-break-after:always;'></table>")
    const thead = $('<thead></thead>')
    const tbody = $('<tbody></tbody>')
    //订单描述区域注入内容
    thead.html(ths)
    tbody.html(trs)
    table.append(thead)
    table.append(tbody)
    return table
}

/**
 * 打印
 * Item {
 *  th:Array[{label:String,value:String,width:String}],订单表头列
 *  data:Object[],数据源
 *  title:String,标题
 *  infos:Array[{label:String,value:String}]详情描述
 * }
 * @param {Item[]} dataSource 
 */
export function toPrintTool(dataSource = []) {
    const px2mm = parseFloat((new unitConversion().pxConversionMm(1)).toFixed(2))
    const maxCount = 5
    //打印内容区域
    let printContent = $(`<div></div>`);
    console.log(dataSource, 'dataSource');
    dataSource.forEach(row => {
        const { th, data, infos, title, tfoot, remark } = row
        // 标题
        let ths = "<tr><th colspan='" + th.length + "'>" + title + "</th></tr>"
        //订单描述内容
        infos.forEach((item, index) => {
            console.log(index % 3);
            if (index % 3 === 0) {
                ths += '<tr> <th class="info_col"  colspan="' + th.length + '">'
            }
            ths += `<span>${item.label || ''}：${item.value || ''}</span>`
            if (index % 3 === 2 || index === infos.length - 1) {
                ths += '</th></tr>'
            }
        })
        ths += "<tr><th colspan='" + th.length + "' class='info_col remark'><div>备注：" + remark + "</div></th></tr>"
        // 组装数据
        let thObj = {}
        th.forEach((td, index) => {
            thObj[td.value] = td.label
        })
        data.unshift(thObj)

        data.push({ ...tfoot })
        const resultData = data.reduce((prev, cur, index, arr) => {
            if (index === arr.length - 1) {
                let tableFoot = "<tr><td colspan='" + th.length + "' class='border0'><div class='tableFoot'>"
                Object.keys(tfoot).forEach(key => {
                    tableFoot += `<span>${key}:</span>`
                })
                tableFoot += "<div></td></tr>"
                prev += tableFoot + '%breakPage%'  // 添加表尾
                return prev

            }
            let str = '<tr>'
            th.forEach(td => {

                if (td.align && index > 0) {
                    str += '<td width="' + td.width + '"><div class="text" data-pageNo="" style="">' + (cur[td.value] || '') + '</div></td>'
                } else {
                    str += '<td width="' + td.width + '"><div class="text" data-pageNo="" style="align-items:center;">' + (cur[td.value] || '') + '</div></td>'
                }
            })
            str += '</tr>'
            prev += (index % maxCount === 0 && index > 0 ? '%breakPage%' + str : str)

            return prev
        }, '')
        resultData.split('%breakPage%').forEach(item => {

            item && printContent.append(createTable(ths, item))
        })
    })
    console.log(dataSource, 'dataSource');
    // 注入页码
    const tables = printContent.find('table')
    const pageTotal = tables.length
    for (let index = 0; index < tables.length; index++) {
        console.log(tables[index]);
        $(tables[index]).attr('data-pageNo', `第${index + 1}/${pageTotal}页`)
    }
    //注入打印内容
    const dom = document.createElement('div')
    dom.setAttribute('id', 'printDom')
    dom.setAttribute('class', 'printDom')
    $(dom).html(printContent.html())
    document.body.appendChild(dom);
    printJs({
        printable: "printDom",
        type: "html",
        style: printStyle(px2mm), // 亦可使用引入的外部css;
        scanStyles: false,

    });
    document.body.removeChild(document.querySelector("#printDom"));
}


// import { makeCode } from '@/utils/makeCode'
/**
 *
 * @param {*} dataSource
 * @param {*} productData
 * @param {boolean} flag  是否限时优惠价信息
 */
export function toPrint(dataSource) {
    let table = ''
    let dom = ''
    const info = `
    <div class='title'>${dataSource.libraryName}出库单</div>
    <div class="info">
        <div class="row">
            <div class="col">
                <span class="label">仓库名称:</span>
                <span class="val">${dataSource.libraryName ? dataSource.libraryName : ''}</span>
            </div>
            <div class="col">
                <span class="label">出库时间:</span>
                <span class="val">${dataSource.outLibraryTime ? dataSource.outLibraryTime : ''}</span>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <span class="label">出库单号:</span>
                <span class="val">${dataSource.code ? dataSource.code : ''}</span>
            </div>
            <div class="col">
                <span class="label">对应单号:</span>
                <span class="val">${dataSource.dataCode ? dataSource.dataCode : ''}</span>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <span class="label">备注:</span>
                <span class="val">${dataSource.remark ? dataSource.remark : ''}</span>      
            </div>
            <div class="col">
                <span class="label">快递单号:</span>
                <span class="val">${dataSource.courierNo ? dataSource.courierNo : ''}</span>      
            </div>
        </div>
    </div>`

    let head = `
            <tr>
            <td width="100px">物料编码</td>
            <td width="180px">物料名称</td>
            <td width="130px">规格型号</td>
          
            <td width="30px">数量</td>
            <td width="50px">单价</td>
            <td width="50px">金额</td>
            <td width="100px">仓库</td>
            <td width="110px">备注</td>
        </tr>`
    let resultDom = ''
    let countTotalResult = 0
    let priceTotalResult = 0
    // 混入合计，签字
    dataSource.stockOutLibraryInfoPrintVoList.push({
        countTotalResult,
        priceTotalResult
    })
    dataSource.stockOutLibraryInfoPrintVoList.push({
        zdrName: '',
        fahuoName: '',
        fuheName: '',
        shName: '',
    })
    const pageTotal = Math.ceil(dataSource.stockOutLibraryInfoPrintVoList.length / 5)


    dataSource.stockOutLibraryInfoPrintVoList.forEach((item, index) => {
        if (index % 5 === 0) {
            dom = `${info} `
            table = ''
            if (index === 0) {
                table = head
            }

        }

        if (index === dataSource.stockOutLibraryInfoPrintVoList.length - 2) {
            table += `<tr>
                <td width="100px">合计：</td>
                <td width="180px"></td>
                <td width="130px"></td>
                <td width="30px">${countTotalResult}</td>
                <td width="50px"></td>
                <td width="50px">${priceTotalResult}</td>
                <td width="100px"></td>
                <td width="110px"></td>
            </tr>`
        } else if (index < dataSource.stockOutLibraryInfoPrintVoList.length - 2) {
            countTotalResult += item.count ? item.count : 0
            priceTotalResult += parseFloat(item.totalPrice >= 0 ? ((item.totalPrice) / 100).toFixed(2) : 0)
            table += `<tr>
            <td width="100px"><div>${item.materialId ? item.materialId : ''}</div></td>
            <td width="180px"><div>${item.materialName ? item.materialName : ''}</div></td>
            <td width="130px"><div>${item.skuStr ? item.skuStr : ''}</div></div></td>
            <td width="30px"><div>${item.count ? item.count : 0}</div></td>
            <td width="50px"><div>${item.unitPrice ? ((item.unitPrice) / 100).toFixed(2) : 0}</div></td>
            <td width="50px"><div>${item.totalPrice ? ((item.totalPrice) / 100).toFixed(2) : 0}</div></td>
            <td width="100px"><div>${item.libraryName ? item.libraryName : ''}</div></td>
            <td width="110px"><div>${item.remark ? item.remark : ''}</div></td>
        </tr>`
        }

        if (index % 5 === 4 || index === dataSource.stockOutLibraryInfoPrintVoList.length - 1) {
            dom += `  
            <div class="goodsInfo">
               <table border='1' cellPadding='0' cellSpacing='0' align="center">
                   <tbody>
                      ${table}
                   </tbody>
               </table>
            </div>
        
            `
            if (index === dataSource.stockOutLibraryInfoPrintVoList.length - 1) {
                dom += `<div class="signName">
                <span>制单人：</span>
                <span>发货人：</span>
                <span>复核人：</span>
                <span>审核人：</span>
            </div>`
            }
            resultDom += dom
        }
    })
    let style = `@page {}
    @media print {
        body { padding: 20px 50px 0px 70px;}
                .printDom{
                    width:750px;
                    position:relative;
                    font-size:12px;
                }
                .title{
                    height:30px;
                    font-weight:600;
                    font-size:16px;
                    text-align:center;
                    padding-top:55px;
                }
                .title:first-child{
                    padding-top:0px;

                }
                .pageNo{
                    text-align:right;
                    margin-top:5px;


                }
                .signName{
                    height:40px;
                    display:flex;
                    align-items:center;
                    justify-content: space-between;
                }
                .signName span{
                    flex:1;
                   
                }
                .info{
                    height:60px;
                }
                .row{
                    display:flex;
                    align-items:center;
                    justify-content: space-between;
                    font-size:12px;
                    margin-bottom:5px;
                }
                .col{
                    flex:1;
                }
                .label{
                    width:100px;
                    text-align:right;
                }
                .val{
                    width:200px;
                }
              
                td{
                    height:50px;
                    font-size:12px;
                    text-align:center;
                }
                td div{
                    width:100%;
                    height:50px;
                    overflow:hidden;
                    display:flex;
                    align-items:center;
                    justify-content: center;
                    white-space:normal;
                    word-break:break-all;
                }
            }
            `
    let div = document.createElement('div')
    div.innerHTML = resultDom
    div.setAttribute('id', 'print_area')
    div.setAttribute('class', 'printDom')
    document.body.appendChild(div)
    printJs({
        printable: 'print_area',
        type: 'html',
        style: style,// 亦可使用引入的外部css;
        scanStyles: false
    })
    document.body.removeChild(document.querySelector('#print_area'))
    return

    // let table = ''
    // dataSource.infoList.forEach((item, index) => {
    //     table += `<tr>
    //         <td>${index + 1}</td>
    //         <td>${item.goodsName ? item.goodsName : ''}</td>
    //         <td>${item.skuName ? item.skuName : ''}</td>
    //         <td>${item.goodsSkuNo ? item.goodsSkuNo : ''}</td>
    //         <td>${item.beforeCount ? item.beforeCount : ''}</td>
    //         <td></td>
    //     </tr>`
    // })
    // let dom = `

    //             <h2 class='title'>${dataSource.dataTypeName}</h2>
    //             <div class="info">
    //                 <table border='0' cellPadding='5' cellSpacing='0'>
    //                     <tbody>
    //                         <tr>
    //                             <td class="label">仓库名称:</td>
    //                             <td class="val">${dataSource.libraryName ? dataSource.libraryName : ''}</td>
    //                             <td class="label">出库时间:</td>
    //                             <td class="val">${dataSource.finishTime ? dataSource.finishTime : ''}</td>
    //                         </tr>
    //                         <tr>
    //                             <td class="label">出库单号:</td>
    //                             <td class="val">${dataSource.code ? dataSource.code : ''}</td>
    //                             <td class="label">对应单号:</td>
    //                             <td class="val">${dataSource.otherCode ? dataSource.otherCode : ''}</td>
    //                         </tr>
    //                         <tr>
    //                             <td class="label">备注:</td>
    //                             <td class="val">${dataSource.remark ? dataSource.remark : ''}</td>      
    //                         </tr>
    //                     </tbody>
    //                 </table>
    //             </div>
    //             <div class="goodsInfo">
    //                     <table border='1' cellPadding='10' cellSpacing='0'>
    //                         <thead>
    //                             <tr>
    //                                 <td>序号</td>
    //                                 <td>物料名称</td>
    //                                 <td>规格</td>
    //                                 <td>物料ID</td>
    //                                 <td>出库数量</td>
    //                                 <td>商品条码</td>
    //                             </tr>
    //                         </thead>
    //                         <tbody>
    //                            ${table}
    //                         </tbody>
    //                     </table>
    //                 </div>
    //             </div>
    //       `
    // let style = `@page { margin: 0; } body { padding: 0px;}
    //         .printDom {
    //             position: relative;
    //             // padding: 10px 20px;
    //             background-color: aqua;
    //             // width: 95%;
    //             left: 5%;
    //         }

    //         .printDom .title {
    //             font-weight: 500;
    //             font-size: 20px;
    //             text-align: center;
    //         }
    //         .printDom .info {
    //             display: flex;
    //             justify-content: space-around;
    //             margin-bottom: 20px;
    //             // margin-left: 20px;
    //             // margin-right: 20px;
    //         }
    //         .printDom .info table{
    //             width: 88%;
    //             table-layout: fixed;
    //             word-wrap: break-word;
    //             margin: 0 auto;
    //         }
    //         .printDom .info table .label{
    //             width: 100px;
    //             text-align: right;
    //         }
    //         .printDom .under{
    //             text-decoration:underline;
    //         }
    //         .printDom .info .orderCode {
    //             // margin-right: 30px;
    //         }
    //         .printDom .orderInfo {
    //             display: flex;
    //             // align-items: center;
    //             font-size: 14px;
    //             letter-spacing: 2px;

    //         }
    //         .printDom .orderInfo .label {
    //             // display: flex;
    //             width: 100px;
    //             text-align: right;
    //         }
    //         .printDom .orderInfo .val {
    //             min-width: 150px;
    //         }
    //         .printDom .goodsInfo table {
    //             width: 88%;
    //             margin-top: 4px;
    //             margin-bottom: 4px;
    //             table-layout: fixed;
    //             word-wrap: break-word;
    //             margin: 0 auto;
    //         }

    //         .printDom .goodsInfo table td {
    //             padding: 5px 20px;
    //             font-size: 14px;
    //             text-align: center;
    //         }

    //         .footer {
    //             font-size: 16px;
    //             margin-top: 4px;

    //         }

    //         .printDom .footer .thanks {
    //             text-align: left;
    //         }

    //         .printDom .footer .tips {
    //             text-align: left;

    //         }

    //         .printDom .footer .tipsText {
    //             font-weight: 600;
    //         }`
    // let div = document.createElement('div')
    // div.innerHTML = dom
    // div.setAttribute('id', 'print_area')
    // div.setAttribute('class', 'printDom')
    // document.body.appendChild(div)
    // printJs({
    //     printable: 'print_area',
    //     type: 'html',
    //     style: style,// 亦可使用引入的外部css;
    //     scanStyles: false
    // })
    // document.body.removeChild(document.querySelector('#print_area'))
}
/*
* tag：所要创建的标签名称
* attrs: 所需要添加的属性，｛key:val,key:val｝
*/
function makeSVG(tag, attrs) {
    const ns = 'http://www.w3.org/2000/svg';
    const xlinkns = 'http://www.w3.org/1999/xlink';

    let el = document.createElementNS(ns, tag);
    if (tag === 'svg') {
        el.setAttribute('xmlns:xlink', xlinkns);
    }
    for (let k in attrs) {
        if (k === 'xlink:href') {
            el.setAttributeNS(xlinkns, k, attrs[k]);
        } else {
            el.setAttribute(k, attrs[k]);
        }
    }
    return el;
}
export function printWaybill(dataSource, sku) {
    console.log(dataSource, 'dataSource');
    let svg = makeSVG('svg', { id: 'barCodeSvg' })
    JsBarcode(svg, dataSource.orderCode, {
        displayValue: false,
        width: 2,
        height: 50,
        margin: 0,
    });

    let dom = document.createElement('div')
    dom.setAttribute('class', 'waybill')
    dom.setAttribute('id', 'barcode')

    dom.innerHTML = `
            <div class="code">${dataSource.orderCode}</div>
            <img src="${logo}" alt="" class="logo" />
            <div class="recipient ">
                <div class="value">
                <div class="name">商户名：</div><div class="txt">${dataSource.storeName}</div>
                </div>
                <div class="value">
                </div>
                <div class="value">
                <div class="name">收货信息：</div><div class="txt">${dataSource.memberAddress}</div>
                </div>
            </div>
            <div class="sku">
                <div class="value"> 
                
                <div class="name">商品明细：</div>
                    <div class="txt">
                    ${sku.join('</br>')}
                    </div>
                </div>
            </div>
            <div class="flag">宠圈顶配，养宠必备</div>
            <div class="tips">哈奇马温馨提示:</div>
            <div class="tipTxt">遇到任何问题，请及时与我们联系，联系电话400-078-1213，我们会尽最大能力为您解决，确保您的购物体验！</div>
            <img src="${wxGong}" alt="" class="wxGong" />
      `
    let canvas = document.createElement('canvas');
    const XML = new XMLSerializer().serializeToString(svg);
    const SVG64 = btoa(XML);
    const image64 = 'data:image/svg+xml;base64,' + SVG64;
    const img = new Image();
    img.onload = function () {
        canvas.getContext('2d').drawImage(img, 0, 0);
    };
    img.src = image64;
    img.setAttribute('class', 'img')
    dom.prepend(img)
    document.body.appendChild(dom)
    let style = `@page { margin: 0; } body { padding: 0px;}
    body { padding: 0px}
    .waybill{
        width:95%;
        font-size:12px;
        position:relative;
    }
    .code{
        text-align: center;
        margin-bottom:0;
        font-size:12px;
    }
    .img{
        width:80%;
        margin:0 0 0 10%;                        
    }
    .wxGong{
        width:80px;
        height:80px;
        position:absolute;
        right:20px;
        bottom:40px;
    }
     .logo {
        width: 60px;
        background-color: #000;
        color:#00;
        margin-left:20px;
    }
    .recipient,.sku{
        border-top:1px dashed #000;
        border-left:1px dashed #000;
        border-right:1px dashed #000;
        border-bottom:1px dashed #000;

        padding:10px 0;
    }
    
    
    .recipient .value,.sku .value{
        padding:0 10px;
        display:flex;
        justify-content:space-between;
    }
    .recipient .value .name,.sku .value .name{
        width:70px;
    }
    .recipient .value .txt,.sku .value .txt{
        width:calc(100% - 75px);
    }
    .flag{
        font-weight:600;
        margin:20px 0 40px;

    }
    .tipTxt{
        font-weight:600;
        

    }
    .sku{
        border-bottom:1px dashed #000;
        display:none;
    }
                `
    setTimeout(() => {
        printJs({
            printable: 'barcode',
            type: 'html',
            style: style,// 亦可使用引入的外部css;
            scanStyles: false
        })
        document.body.removeChild(document.querySelector('#barcode'))
    }, 0);
}

export function printLogo() {

    const dom = `<img src="${NewLogo}" alt="" class="logo1" />13123123123<img src="${NewLogo}" alt="" class="logo2" />`
    let div = document.createElement('div')
    div.innerHTML = dom
    div.setAttribute('id', 'print_area')
    div.setAttribute('class', 'printDom')
    document.body.appendChild(div)
    printJs({
        printable: 'print_area',
        type: 'html',
        style: `
                @page { margin: 0;size:portrait ;count:100} 
                body { padding: 0px;position:relative;}
                .logo1{position:absolute;width:100px;height:120px;left:-5px;top:220px}
                .logo2{position:absolute;width:100px;height:120px;left:-5px;top:50px}
                `,// 亦可使用引入的外部css;
        scanStyles: false
    })

}
